package business.search_eng;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONStringer;

import business.search_eng.scorer.WeightedScorer;

public class PostingList implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -6873279406322122793L;
	
	public String word;
	public ArrayList<PostingListItem> documents;
	
	public HashMap<String, Double> scores;
	public HashMap<String, Double> weights;
	//public Double invertedDocumentFrequency;
	//public Double reputation;
	
	public PostingList (String word) {
		this.word = word;
		this.documents = new ArrayList<PostingListItem>();
		//this.invertedDocumentFrequency = null;
		
		this.scores = new HashMap<String, Double>();
		this.weights = new HashMap<String, Double>();
		
		scores.put("idf", 0.0);
		weights.put("idf", 1.0);
		
		scores.put("reputation", 0.0);
		weights.put("reputation", 2.0);


	}
	
	public void addDocument(PostingListItem id) {
		this.documents.add(id);
	}

	public void calculateScores() {
		int it=0;
		while(it < this.documents.size()) {
			PostingListItem tmp = this.documents.get(it);
			tmp.calculateScore(scores, weights);
			it++;
		}
	}
	
	public void sortByScore() {
		try {
			Collections.sort(this.documents);
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	public String JSONstringify() {
		StringBuilder sb = new StringBuilder();
		Iterator<PostingListItem> it = this.documents.iterator();
		sb.append("[");
		boolean first = true;
		while (it.hasNext()) {
			if (first) {first= false;}
			else {sb.append(",");}
			sb.append (it.next().documentId);
		}
		sb.append("]");
		return sb.toString();
	}
	
   /**
   * Always treat de-serialization as a full-blown constructor, by
   * validating the final state of the de-serialized object.
   */
   private void readObject(java.io.ObjectInputStream in)
   				throws ClassNotFoundException, IOException {
	   //always perform the default de-serialization first
	   in.defaultReadObject();
   }

	/**
	* This is the default implementation of writeObject.
	* Customise if necessary.
	*/
   private void writeObject(java.io.ObjectOutputStream out)
   				throws IOException {
	   //perform the default serialization for all non-transient, non-static fields
	   out.defaultWriteObject();
   }
}
